package cn.sccl.common.web;


import cn.sccl.common.model.QueryData;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by 杨浩宇 on 2016-02-18.
 */
public class BaseController {

    protected Log log = LogFactory.getLog(this.getClass());

    public QueryData getQueryData(HttpServletRequest request) {
        QueryData queryData = new QueryData();
        Map<String, String[]> properties = request.getParameterMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            queryData.put(name, value);
        }
        return queryData;
    }

    /**
     * 从get参数中分解出分页页码
     *
     * @param request
     * @return
     */
    public long getPageIndex(HttpServletRequest request) {
        String page = request.getParameter("page");
        if (!StringUtils.isBlank(page) && page.matches("^[1-9]\\d*$")) {
            return Long.valueOf(page);
        }
        return 1;
    }

    /**
     * 从get参数中分解出分页大小
     *
     * @param request
     * @return
     */
    public int getPageSize(HttpServletRequest request) {
        String page = request.getParameter("rows");
        if (!StringUtils.isBlank(page) && page.matches("^[1-9]\\d*$")) {
            return Integer.valueOf(page);
        }
        return 10;
    }
}
